from django.db import models
from product.models import Product

# 库存模型
class Inventory(models.Model):
    product = models.OneToOneField(
        Product,
        on_delete=models.CASCADE,
        related_name='inventory',
        verbose_name='商品'
    )
    quantity = models.IntegerField(
        verbose_name='库存量'
    )
    low_stock_threshold = models.IntegerField(
        default=10,
        verbose_name='低库存阈值'
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )

    class Meta:
        verbose_name = '库存'
        verbose_name_plural = '库存管理'
        db_table = "inventory_inventory"

    def __str__(self):
        return f'{self.product.name} - 库存: {self.quantity}'

    @property
    def is_low_stock(self):
        return self.quantity <= self.low_stock_threshold

# 库存变动记录
class InventoryLog(models.Model):
    IN_TYPE = 'in'
    OUT_TYPE = 'out'
    
    TRANSACTION_TYPES = [
        (IN_TYPE, '入库'),
        (OUT_TYPE, '出库'),
    ]
    
    inventory = models.ForeignKey(
        Inventory,
        on_delete=models.CASCADE,
        related_name='logs',
        verbose_name='库存'
    )
    quantity_change = models.IntegerField(
        verbose_name='数量变动'
    )
    transaction_type = models.CharField(
        max_length=10,
        choices=TRANSACTION_TYPES,
        verbose_name='交易类型'
    )
    remark = models.CharField(
        max_length=200,
        blank=True,
        null=True,
        verbose_name='备注'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='变动时间'
    )
    created_by = models.ForeignKey(
        'user.Cashier',
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        verbose_name='操作人'
    )

    class Meta:
        verbose_name = '库存变动记录'
        verbose_name_plural = '库存变动记录管理'
        ordering = ['-created_at']
        db_table = "inventory_inventorylog"

    def __str__(self):
        return f'{self.get_transaction_type_display()} - {self.inventory.product.name} - {self.quantity_change}'
